package com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.detail;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.mcas.http.imageloader.glide.GlideArms;
import com.kaiwukj.android.mcas.utils.McaUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.BaseSwipeBackFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerDynamicComponent;
import com.kaiwukj.android.ufamily.di.module.DynamicModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.HomeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.CommentParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.CommentReplyParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.CommentResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DynamicResult;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.NineGridIvAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.DynamicContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.report.ReportCardFragment;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.DialogUtilsKt;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.ISupportFragment;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;


/**
 * Copyright © KaiWu Technology Company
 *
 * @author Haife
 * @job Android Development
 * @company KW | 开物科技
 * @time 2019/7/19
 * @desc 社交圈子帖子
 */
public class DynamicDetailFragment extends BaseSwipeBackFragment<DynamicPresenter> implements DynamicContract.View {

    @BindView(R.id.smart_refresh_card_detail)
    SmartRefreshLayout mSmartRefresh;
    @BindView(R.id.qmui_empty_view_card_detail)
    QMUIEmptyView mEmptyView;
    @BindView(R.id.rv_dynamic_detail_comment)
    RecyclerView mRvComment;
    @BindView(R.id.rl_circle_detail_container)
    ViewGroup mCircleCardContainer;
    @BindView(R.id.qriv_circle_head_photo)
    QMUIRadiusImageView mUserHeadIv;
    @BindView(R.id.tv_circle_nick_name)
    TextView mNickNameTv;
    @BindView(R.id.tv_circle_publish_time)
    TextView mTimeTv;
    @BindView(R.id.qbtn_collection)
    QMUIRoundButton mCollection;
    @BindView(R.id.tv_circle_message_content)
    TextView mContentTv;
    @BindView(R.id.container_media)
    ViewGroup containerMedia;
    @BindView(R.id.container_video)
    ViewGroup containerVideo;
    @BindView(R.id.iv_cover)
    ImageView ivCover;
    @BindView(R.id.iv_video_play)
    ImageView ivVideoPlay;
    @BindView(R.id.btn_topic)
    QMUIRoundButton btnTopic;
    @BindView(R.id.container_input)
    ViewGroup containerInput;
    @BindView(R.id.container_input_view)
    ViewGroup containerInputView;

    @BindView(R.id.et_social_circle_reply_comment)
    EditText mCommentEt;
    @BindView(R.id.tv_input_view)
    TextView tvInputView;
    @BindView(R.id.iv_good)
    ImageView ivGood;
    @BindView(R.id.tv_good_num)
    TextView tvGoodNum;
    @BindView(R.id.tv_comment_num)
    TextView tvCommentNum;
    @BindView(R.id.btn_comment_send)
    Button btnCommentSend;

    @BindView(R.id.rv_circle_card_detail_images)
    NineGridView mImageGroup;
    private TextView tvExpand;//adapter footerView
    private DynamicCommentAdapter mCommentAdapter;
    private NineGridIvAdapter mGridIvAdapter;
    public static final String CIRCLE_CARD_DETAIL = "CIRCLE_CARD_DETAIL";
    public static final String CIRCLE_CARD_DETAIL_ID = "CIRCLE_CARD_DETAIL_ID";
    private int page = 1;
    private DynamicResult mDynamicResult;
    private int mDynamicId = -1;
    //是否关注
    private MaterialDialog mBottomMaterialDialog;
    private QMUITopBar topBar;

    private int commentPageSize = 10;
    private boolean isLoadingMore = false;

    private boolean isLoadChildMore = false;

    private boolean isFirst = true;

    private int reqPos = -1;//child请求pos(所属parent position)

    private int commentType = 0;//0为评论动态 评论人类型：1针对评论的回复 2针对回复
    private CommentResult toCommentResult;//评论对象

    private boolean isMine = false;

    @OnClick(R.id.btn_topic)
    void onTopicClick() {
        if (mDynamicResult != null && mDynamicResult.getTopicId() > 0) {
            ARouter.getInstance().build(ARouterUrlKt.TopicIndexUrl)
                    .withInt("topicId", mDynamicResult.getTopicId())
                    .navigation(getContext(), new NavigationCallback() {
                        @Override
                        public void onFound(Postcard postcard) {

                        }

                        @Override
                        public void onLost(Postcard postcard) {

                        }

                        @Override
                        public void onArrival(Postcard postcard) {
                            if (getActivity() != null) {
                                getActivity().finish();
                            }
                        }

                        @Override
                        public void onInterrupt(Postcard postcard) {

                        }
                    });
        }
    }

    @OnClick({R.id.iv_good, R.id.iv_comment})
    void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.iv_good:
                if (mDynamicResult.isPraise()) {
                    mPresenter.cancelPraise(mDynamicResult.getId());

                } else {
                    mPresenter.praise(mDynamicResult.getId());
                }
                break;
            case R.id.iv_comment:
                // mPresenter.
                break;
        }
    }

    public static ISupportFragment newInstance(int id) {
        DynamicDetailFragment fragment = new DynamicDetailFragment();
        fragment.mDynamicId = id;
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerDynamicComponent
                .builder()
                .appComponent(appComponent)
                .dynamicModule(new DynamicModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dynamic_detail;
    }


    @Override
    protected void initView() {
        assert getActivity() != null;
        topBar = this.getActivity().findViewById(R.id.qtb_social_circle);
        initTopBar(topBar);
        topBar.removeAllRightViews();
        topBar.setTitle(getString(R.string.social_circle_theme_card));
        if (getApp().getUserInfo() == null) return;

        tvInputView.setOnClickListener(v -> openCommentInput());
        KeyboardUtils.registerSoftInputChangedListener(Objects.requireNonNull(getActivity()), height -> {
            if (height > 0) {
                containerInput.setVisibility(View.VISIBLE);
                containerInputView.setVisibility(View.GONE);
            } else {
                commentType = 0;
                containerInput.setVisibility(View.GONE);
                containerInputView.setVisibility(View.VISIBLE);
                mCommentEt.setHint(R.string.social_circle_reply_comment_hint);
            }
        });
        initRvItemClick();
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        assert mPresenter != null;
        mEmptyView.show(true);
        mPresenter.getDynamicById(mDynamicId);
        /*} else {
            loadUI(mDynamicResult);
        }*/
    }

    private void initRvItemClick() {
        mSmartRefresh.setEnableLoadMore(false);
        // mRvComment.setNestedScrollingEnabled(false);
        // mRvComment.setHasFixedSize(true);
        mRvComment.addItemDecoration(new SpaceItemDecoration(1));
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        //layoutManager.setSmoothScrollbarEnabled(true);
        //McaUtils.configRecyclerView(mRvComment, layoutManager);

        //mCommentAdapter = new SocialCardCommentAdapter();
        //mCircleCardCommentRv.setAdapter(mCommentAdapter);
        mRvComment.setLayoutManager(layoutManager);
        mCommentAdapter = new DynamicCommentAdapter();
        View footerView = View.inflate(getContext(), R.layout.item_comment_parent_footer, null);
        tvExpand = footerView.findViewById(R.id.tv_expand);
        tvExpand.setText("展开全部评论");
        tvExpand.setOnClickListener(v -> {
            mSmartRefresh.setEnableLoadMore(true);
            mSmartRefresh.autoLoadMore();
            mCommentAdapter.removeFooterView(footerView);
        });
        mCommentAdapter.setFooterView(footerView);
        mRvComment.setAdapter(mCommentAdapter);
        mCommentAdapter.setOnCommentDataLoader((parentPos, replyId, startId, pageSize) -> {
            reqPos = parentPos;
            mPresenter.fetchReply(replyId, startId, pageSize);
        });
        mCommentAdapter.setOnComment((type, parentPos, childPos, result) -> {
            if (result.getFromUid().equals(getApp().getUserInfo().getId())) {
                showMessageOKCancel(getActivity(), "删除我的评论", v -> {
                    mPresenter.delComment(type, result.getId());
                    if (type == 1) {
                        mCommentAdapter.removeAt(parentPos);
                    } else {
                        mCommentAdapter.removeChild(parentPos, childPos);
                    }
                });
            } else {
                openCommentInput();
                commentType = type;
                reqPos = parentPos;
                toCommentResult = result;

                if (type == 2) {
                    //mReplyId = result.getReplyId();
                    // mToUId = result.getFromUid();
                    mCommentEt.setHint(String.format("回复 %s:", result.getFromNickname()));
                } else {
                    // mReplyId = result.getId();
                    //mToUId = result.getId();
                    mCommentEt.setHint("回复评论:");
                }
            }
        });


        btnCommentSend.setOnClickListener(v -> {
            //评论别人
            String content = mCommentEt.getText().toString().trim();
            if (StringUtils.isEmpty(content)) {
                showMessage("内容不能为空!");
                return;
            }
            if (commentType != 0) {
                CommentReplyParams params = new CommentReplyParams();
                params.setReplyType(commentType);
                params.setCommentContent(content);
                params.setReplyId(commentType == 2 ? toCommentResult.getReplyId() : toCommentResult.getId());
                params.setToUid(commentType == 2 ? toCommentResult.getFromUid() : toCommentResult.getId());
                mPresenter.commentReply(params, reqPos);

            } else {
                CommentParams params = new CommentParams();
                params.setDynamicId(mDynamicResult.getId());
                params.setCommentContent(content);
                mPresenter.comment(params);
            }
        });

        mCommentEt.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND) {
                //评论别人
                String content = mCommentEt.getText().toString().trim();
                if (StringUtils.isEmpty(content)) {
                    showMessage("内容不能为空!");
                }
                if (commentType != 0) {
                    CommentReplyParams params = new CommentReplyParams();
                    params.setReplyType(commentType);
                    params.setCommentContent(content);
                    params.setReplyId(commentType == 2 ? toCommentResult.getReplyId() : toCommentResult.getId());
                    params.setToUid(commentType == 2 ? toCommentResult.getFromUid() : toCommentResult.getId());
                    mPresenter.commentReply(params, reqPos);

                } else {
                    CommentParams params = new CommentParams();
                    params.setDynamicId(mDynamicResult.getId());
                    params.setCommentContent(content);
                    mPresenter.comment(params);
                }
                //   mPresenter.requestCommentOther(mCommentOtherRequest);
            }
            return true;
        });

        //关注其他人
        mCollection.setOnClickListener(view -> {
            assert mPresenter != null;
            if (mDynamicResult.isAttention()) {
                showMessageOKCancel(getActivity(), "是否不再关注TA", v ->
                        mPresenter.cancelAttention(mDynamicResult.getUserId()));

            } else {
                mPresenter.attention(mDynamicResult.getUserId());
            }
        });
        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadingMore = true;
                mPresenter.fetchComment(mDynamicResult.getId(), (int) mCommentAdapter.getLastItemId(), commentPageSize);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getDynamicById(mDynamicResult.getId());
            }
        });

    }


    private void initTopBar(QMUITopBar topBar) {
        topBar.addLeftBackImageButton().setOnClickListener(view -> {
            if (getActivity() != null) {
                getActivity().onBackPressed();
            }
        });
        topBar.setTitle(getString(R.string.social_circle_theme_card));
    }

    /**
     * 初始化ImageViwe
     */
    private void initGroupImageAdapter(List<String> imageList) {
        ArrayList<ImageInfo> imageInfo = new ArrayList<>();
        for (int i = 0; i < imageList.size(); i++) {
            ImageInfo info = new ImageInfo();
            info.setThumbnailUrl(imageList.get(i));
            info.setBigImageUrl(imageList.get(i));
            imageInfo.add(info);
        }
        //单张图片的大小
        mGridIvAdapter = new NineGridIvAdapter(getContext(), imageInfo);
        mImageGroup.setSingleImageSize(McaUtils.getScreenWidth(getContext()) / 2);
        mImageGroup.setAdapter(mGridIvAdapter);
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }

    @Override
    public void onFetchDynamic(List<DynamicResult> results) {

    }

    @Override
    public void onGetDynamic(DynamicResult result) {
        mEmptyView.hide();
        mSmartRefresh.finishRefresh();
        mDynamicResult = result;
        loadUI(result);
    }

    @Override
    public void onGetComment(List<CommentResult> results, boolean isChild) {
        loadComment(results, isChild);
    }

    @Override
    public void onCommentResult(int id, CommentParams params) {
        CommentResult result = new CommentResult();
        result.setId(id);
        result.setCommentContent(params.getCommentContent());
        result.setFromUid(getApp().getUserInfo().getId());
        result.setCreateTime(TimeUtils.getNowString());
        result.setHeadImg(getApp().getUserInfo().getHeadImg());
        result.setNickname(getApp().getUserInfo().getNickName());
        result.setToUid(getApp().getUserInfo().getId());
        mCommentAdapter.addData(0, result);

        mCommentEt.setText("");
        commentType = 0;
        Map<String, Object> map = new HashMap<>();
        map.put("commentId", id);
        map.put("commentParams", params);
        EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_COMMENT, map, mDynamicId));
    }

    @Override
    public void onReplyResult(int parentPos, int id, CommentReplyParams params) {
        CommentResult result = new CommentResult();
        result.setReplyId(params.getReplyId());
        result.setReplyType(params.getReplyType());
        result.setToUid(toCommentResult.getFromUid());
        result.setFromNickname(getApp().getUserInfo().getNickName());
        result.setFromUid(getApp().getUserInfo().getId());
        result.setToNickname(toCommentResult.getFromNickname());
        result.setId(id);
        result.setCommentContent(params.getCommentContent());
        List<CommentResult> data = new ArrayList<>();
        data.add(result);
        mCommentAdapter.addChildData(parentPos, data);

        mCommentEt.setText("");
        commentType = 0;
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        switch (taskId) {
            case DynamicPresenter.ATTENTION:
                showMessage(getString(R.string.social_circle_attention_success));
                mDynamicResult.attention(true);
                mCollection.setText(getString(R.string.social_circle_cancel_attention));
               // mCollection.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.gray_f2));
                EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_ATTENTION, mDynamicResult.getUserId(), mDynamicId));
                break;
            case DynamicPresenter.ATTENTION_CANCEL:
                showMessage(getString(R.string.social_circle_cancel_attention_hint));
                mDynamicResult.attention(false);
                mCollection.setText(getString(R.string.social_circle_attention_str));
                //mCollection.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorAccent));
                EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_ATTENTION_CANCEL, mDynamicResult.getUserId(), mDynamicId));
                break;
            case DynamicPresenter.PRAISE:
                mDynamicResult.praise(true);
                ivGood.setImageResource(R.mipmap.ic_dynamic_good_checked);
                mDynamicResult.setThumbNum(mDynamicResult.getThumbNum() + 1);
                tvGoodNum.setText(String.valueOf(mDynamicResult.getThumbNum()));
                EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_LIKE, mDynamicId));
                break;
            case DynamicPresenter.PRAISE_CANCEL:
                mDynamicResult.praise(false);
                ivGood.setImageResource(R.mipmap.ic_dynamic_good);
                mDynamicResult.setThumbNum(mDynamicResult.getThumbNum() - 1);
                tvGoodNum.setText(String.valueOf(mDynamicResult.getThumbNum()));
                EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_LIKE_CANCEL, mDynamicId));
                break;
            case DynamicPresenter.BLOCK:
                EventBus.getDefault().post(new HomeEvent(HomeEvent.DYNAMIC_BLOCK, mDynamicId));
                killMyself();
                break;
            case DynamicPresenter.BLOCK_USER:
                EventBus.getDefault().post(new HomeEvent(HomeEvent.USER_BLOCK));
                killMyself();
                break;
            case DynamicPresenter.DELETE:
                EventBus.getDefault().post(new HomeEvent(HomeEvent.DYNAMIC_DELETE, mDynamicId));
                killMyself();
                break;
            case DynamicPresenter.COMMENT_DELETE:
                EventBus.getDefault().post(new HomeEvent(HomeEvent.DELETE_COMMENT, mCommentAdapter.getData(), mDynamicId));
                break;
        }
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        mSmartRefresh.finishRefresh(false);
        mSmartRefresh.finishLoadMore(false);
        mEmptyView.hide();
        hideLoading();
    }

    private void loadUI(DynamicResult result) {

        isMine = mDynamicResult.getUserId().equals(getApp().getUserInfo().getId());
        if (isMine) {
            mCollection.setVisibility(View.GONE);
        } else {
            if (mDynamicResult.isAttention()) {
                mCollection.setText("已关注");
                mCollection.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.gray_f2));
            } else {
                mCollection.setText("关注");
                mCollection.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorAccent));
            }
        }


        if (isFirst) {
            isFirst = false;
            topBar.addRightImageButton(R.drawable.ic_card_detail_report, R.id.qmui_top_right_btn).setOnClickListener(view -> {
                mBottomMaterialDialog = DialogUtilsKt.showBottomReportDialog(Objects.requireNonNull(getContext()), view1 -> {
                    switch (view1.getId()) {
                        //屏蔽帖子
                        case R.id.tv_block_this_content:
                            mPresenter.blockUserOrDynamic(mDynamicResult.getId(), true, false);
                            mBottomMaterialDialog.dismiss();
                            break;
                        //屏蔽用户
                        case R.id.tv_block_this_user:
                            // BlockCardOrUserRequest requestUser = new BlockCardOrUserRequest(cardUserId, 2);
                            //assert mPresenter != null;
                            // mPresenter.requestBlockUserOrCard(requestUser);
                            mPresenter.blockUserOrDynamic(mDynamicResult.getUserId(), true, true);
                            mBottomMaterialDialog.dismiss();
                            break;
                        //举报
                        case R.id.tv_report_this_user:
                            mBottomMaterialDialog.dismiss();
                            start(ReportCardFragment.newInstance(mDynamicResult));
                            break;
                        case R.id.tv_delete:
                            //    mPresenter.delSocialCard(mCardId);
                            showLoading("正在请求...");
                            mPresenter.delDynamic(mDynamicResult.getId());
                            mBottomMaterialDialog.dismiss();
                            break;
                    }
                }, isMine);
            });
        }

        assert getContext() != null;
        tvGoodNum.setText(String.valueOf(result.getThumbNum()));
        tvCommentNum.setText(String.valueOf(result.getCommentNum()));
        //tvExpand.setText(String.format("展开%s条评论", result.getCommentNum()));
        if (commentPageSize > result.getCommentNum()) {
            tvExpand.setVisibility(View.GONE);
        }
        ivGood.setImageResource(mDynamicResult.isPraise() ? R.mipmap.ic_dynamic_good_checked : R.mipmap.ic_dynamic_good);

        GlideArms.with(getContext()).load(result.getHeadImg()).circleCrop().into(mUserHeadIv);
        mNickNameTv.setText(result.getUserName());
        mTimeTv.setText(TimeUtils.getFriendlyTimeSpanByNow(result.getCreateTime()));
        mContentTv.setText(result.getDynamicContent());
        if (StringUtils.isEmpty(result.getTopicTitle())) {
            btnTopic.setVisibility(View.GONE);
        } else {
            btnTopic.setText(result.getTopicTitle());
        }
        if (result.isAttention()) {
            mCollection.setText(getString(R.string.social_circle_cancel_attention));
        } else {
            mCollection.setText(getString(R.string.social_circle_attention_str));
        }
        /*if (!TextUtils.isEmpty(mCircleHomeResult.getNoteTypeName())) {
            //mContentTv.setText(generateSp(mCircleHomeResult));
            mContentTv.setTagText(String.format("#%s", mCircleHomeResult.getNoteTypeName()));
        }
        mContentTv.setOnTagClickListener(v -> ARouter.getInstance()
                .build(ARouterUrlKt.CircleListUrl)
                .withInt(ExtraCons.CIRCLE_TOPIC_TYPE_ID, mCircleHomeResult.getType())
                .withString(ExtraCons.CIRCLE_TOPIC_TYPE_TITLE, mCircleHomeResult.getNoteTypeName())
                .navigation());*/

        if (!StringUtils.isEmpty(result.getVideo())) {
            containerMedia.setVisibility(View.VISIBLE);
            containerVideo.setVisibility(View.VISIBLE);
            mImageGroup.setVisibility(View.GONE);
            Glide.with(this)
                    .load(result.getImages())
                    .into(ivCover);
            ivVideoPlay.setOnClickListener(v ->
                    ARouter.getInstance().build(ARouterUrlKt.VideoPlay)
                            .withString("videoUrl", result.getVideo())
                            .withString("coverUrl", result.getImages())
                            .withString("title", result.getDynamicContent())
                            .navigation());
        } else if (!StringUtils.isEmpty(result.getImages())) {
            containerMedia.setVisibility(View.VISIBLE);
            containerVideo.setVisibility(View.GONE);
            mImageGroup.setVisibility(View.VISIBLE);
            initGroupImageAdapter(Arrays.asList(result.getImages().split(",")));
        } else {
            containerMedia.setVisibility(View.GONE);
        }

        mPresenter.fetchComment(result.getId(), 0, commentPageSize);

    }

    /**
     * 加载评论数据
     *
     * @param commentResults data
     * @param isChild        是子评论
     */
    private void loadComment(List<CommentResult> commentResults, boolean isChild) {
        if (!isChild) {
            if (isLoadingMore) {
                isLoadingMore = false;
                mCommentAdapter.addData(commentResults);
                if (commentResults.size() < commentPageSize) {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                } else {
                    mSmartRefresh.finishLoadMore();
                }
            } else {
                //mCommentAdapter.getData().clear();
                mCommentAdapter.setList(commentResults);
            }
        } else {
            mCommentAdapter.addChildData(reqPos, commentResults);
            reqPos = -1;
        }
    }

    private void openCommentInput() {
        if (getActivity() != null) {
            mCommentEt.requestFocus();
            mCommentEt.setFocusable(true);
            mCommentEt.setFocusableInTouchMode(true);
            KeyboardUtils.showSoftInput(getActivity());
        }
    }

    @Override
    public void onDetach() {
        if (getActivity() != null) {
            KeyboardUtils.unregisterSoftInputChangedListener(getActivity().getWindow());
        }
        super.onDetach();

    }
}


